// SPDX-License-Identifier: GPL-2.0+
/*
 * (C) Copyright 2021 maoxiaochuan <maoxiaochuan@loongson.cn>
 */

#include <common.h>
#include <command.h>
#include <env.h>
#include <watchdog.h>
#include <malloc.h>
#include <linux/string.h>
#include <linux/fb.h>

#include "loongson_update.h"


char *rotation_menu[] = {
	"normal orientation (0 degree)=0",
	"clockwise orientation (90 degrees)=1",
	"upside down orientation (180 degrees)=2",
	"counterclockwise orientation (270 degrees)=3",
	NULL
};

static void set_rotation(char *rotation)
{
	char option[256] = {0};
	char *bootargs = env_get("bootargs");
	if (bootargs) {
		strcpy(option, bootargs);
		char *dest_str = "fbcon=rotate:";
		char *p = strstr(option, dest_str);
		if (p) {
			int pos = p - option + strlen(dest_str);
			option[pos] = rotation[0];
		} else {
			char tmp[32] = {0};
			snprintf(tmp, sizeof(tmp), " %s%s", dest_str, rotation);
			strcat(option, tmp);
		}
		printf("bootargs:%s\n", option);

		env_set("bootargs", option);
#if defined(CONFIG_CONSOLE_ROTATION)
		env_set("rotation", rotation);
#endif
		env_save();
	}
}

void update_rotation(char *command, unsigned short num)
{
	cmd_tbl_t *cmdtp;
	
	/* Look up command in command table */
	cmdtp = find_cmd(command);
	if ((cmdtp == NULL) && (command[0] != '\0') && (num < 4)) {
		set_rotation(command);
	} else {
		run_command(command, 0);
	}
}

int do_rotation_menu(cmd_tbl_t *cmdtp, int flag, int argc, char *const argv[])
{
	updatemenu_type = UPDATE_TYPE_ROTATION;
	updatemenu_return = UPDATEMENU_RETURN_CONSOLE;
	updatemenu_show();

	return 0;
}

U_BOOT_CMD(
	rotation_menu, 2, 1, do_rotation_menu,
	"ANSI terminal rotation_menu",
	"command to select rotation degree"
);
